<template>
  <div>
    <el-dialog
      :visible.sync="formShow"
      @close="handleClickDeal('cancel')"
      v-dialog-drag
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      width="60%"
    >
      <span slot="title">
        <span>质量类别问题管理</span>{{editType}}
      </span>
      <div class="dialog-box">
        <div class="rightButtonBox">
          <el-button class="blueButton" @click="addFather()">+新增根节点</el-button>
        </div>
        <el-table
          :header-cell-style="{textAlign:'center',padding: '8px 0',backgroundColor: '#f2f2f2',borderColor: '#d4d4d4'}"
          :cell-style="{padding: '6px 0',borderColor: '#d4d4d4'}"
          class="allplan-manage-detail-table"
          ref="allplanTable"
          :data="treeData"
          style="margin-bottom: 20px;"
          width="100%"
          height="666"
          row-key="id"
          border
          lazy
          :tree-props="{children: 'childList', hasChildren: 'hasChildren'}"
        >
          <el-table-column
            prop="name"
            label="质量问题类别名称"
            style="position: sticky"
            min-width="260"
          >
            <template slot-scope="scope">
              {{scope.row.name}}
            </template>
          </el-table-column>
          <el-table-column
            prop="code"
            label="操作"
            style="position: sticky"
            width="250"
          >
            <template slot-scope="scope">
              <div class="actionSpan">
                <el-button @click="addSon(scope.row)" class="blueButton">+新增子项</el-button>
                <el-button @click="edit(scope.row)" class="greenButton">编辑</el-button>
                <el-button @click="del(scope.row)" class="redButton">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!--  -->
      <el-dialog
        width="35%"
        :visible.sync="showAddDialog"
        :modal-append-to-body="false"
        :close-on-click-modal="false"
        v-dialog-drag
        append-to-body>
            <span slot="title">
             <span>新增子项</span>
            </span>
        <el-form :model="addNewForm" ref="formBaseData" :rules="formBaseRules" class="measurepaycompensation_detail_form">
          <el-row v-if="!isAddRoot">
            <el-col :span="24">
              <el-form-item  label="路径" prop="fatherName" :label-width="formlabelWidth">
                <el-input size="small" v-model="addNewForm.fatherName" placeholder=""
                          disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item  label="类别名称" prop="name" :label-width="formlabelWidth">
                <el-input  size="small"  v-model="addNewForm.name" placeholder=""></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <!--新建和编辑的暂存上报-->
          <template>
            <el-button
              size="small"
              type="primary"
              @click="handleAdd('add')"
            ><i class="iconfont icon-icon_save"></i> 确 定</el-button>
          </template>
          <el-button size="small" @click="handleCancel"><i class="iconfont icon-icon_cancel"></i> 取 消</el-button>
        </div>
      </el-dialog>


      <el-dialog
        width="35%"
        :visible.sync="showEditDialog"
        :modal-append-to-body="false"
        :close-on-click-modal="false"
        v-dialog-drag
        append-to-body>
            <span slot="title">
             <span>编辑{{editType}}项</span>
            </span>
        <el-form :model="editForm" ref="editFormBaseData" :rules="formBaseRules" class="measurepaycompensation_detail_form">
          <el-row v-if="editType == '子'">
            <el-col :span="24">
              <el-form-item  label="路径" prop="fatherName" :label-width="formlabelWidth">
                <el-input size="small" v-model="editForm.fatherName" placeholder=""
                          disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item  label="类别名称" prop="name" :label-width="formlabelWidth">
                <el-input  size="small"  v-model="editForm.name" placeholder=""></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <!--新建和编辑的暂存上报-->
          <template>
            <el-button
              size="small"
              type="primary"
              @click="handleAdd('edit')"
            ><i class="iconfont icon-icon_save"></i> 确 定</el-button>
          </template>
          <el-button size="small" @click="handleCancel"><i class="iconfont icon-icon_cancel"></i> 取 消</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import msgUtil from "@/utils/msgUtil";

export default {
  props: {
    postDetail: {
      type: Object,
      default: {
        show: false
      }
    }
  },
  watch: {
    postDetail(value) {
      // 显示详情弹窗
      this.formShow = value.show
      this.$set(this,'search',value.search)
      this.getTableData()
      //前端处理treeData  模拟 isLeaf   后期删除该方法
      console.log(this.treeData)
    }
  },
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      editType:'',
      treeData:[],
      formShow:false,
      showAddDialog:false,
      showEditDialog:false,
      isAddRoot:false,
      chooseTreeData:{},
      chooseTreeFatherData:{},
      troubleTypeArr:[],
      addNewForm:{
        isStump:'', // 是否根节点
        sectionId:'',
        projectId:'',
        pid:'',
        fatherName: '',
        name: '',
        pxRank: '',
        isLeaf: ''
      },
      search: {
        sectionId: '',
        projectId:''
      },
      editForm:{
        id:'',
        isStump:'', // 是否根节点
        sectionId:'',
        projectId:'',
        pid:'',
        fatherName: '',
        name: '',
        pxRank: '',
        isLeaf: ''
      },
      formlabelWidth: '140px',
      formBaseRules: {
        fatherName: [
          {required: true, message: '请输入' + '上级名称', trigger: 'blur'},
        ],
        name: [
          {required: true, message: '请输入' + '名称', trigger: 'blur'},
        ],
        isLeaf: [
          {required: true, message: '请选择' + '是否叶子节点', trigger: 'blur'},
        ],
      },
    }
  },
  methods: {
    handleAdd(type){
      if(type == 'add'){
        this.addNewForm.projectId = this.search.projectId;
        this.addNewForm.sectionId = this.search.sectionId;

        this.$refs['formBaseData'].validate((valid) => {
          if (valid) {
            this.$httpPost('buss/inspectionQuestionMain/add',this.addNewForm).then(res=>{
              this.showAddDialog = false
              this.getTableData()
              this.handleCancel()
            }).catch(res=>{
              console.log(res)
            })
          }
        })
      }
      if(type == 'edit'){
        this.$refs['editFormBaseData'].validate((valid) => {
          if (valid) {
            this.$httpPost('buss/inspectionQuestionMain/edit',this.editForm).then(res=>{
              this.showEditDialog = false
              this.getTableData()
              this.handleCancel()
            }).catch(res=>{
              console.log(res)
            })
          }
        })
      }
    },
    getTableData(){
      let postData = {
        projectId: this.search.projectId,
      }
      this.$httpPost('buss/inspectionQuestionMain/getAllByProjectId',postData).then(res=>{
        this.$set(this,'treeData',res.data)
        console.log(this.treeData,'treeData')
      }).catch(res=>{

      })
    },
    handleCancel(){
      this.$emit('reloadList')
      this.showAddDialog = false
      this.showEditDialog = false
      this.isAddRoot = false
      this.editForm = {
        projectId:'',
        sectionId:'',
        fatherName: '',
        name: '',
        pxRank: '',
        isLeaf: ''
      }
      this.addNewForm = {
        projectId:'',
        sectionId:'',
        fatherName: '',
        name: '',
        pxRank: '',
        isLeaf: ''
      }

    },

    // 新增根节点
    addFather(){
      this.addNewForm.pid = '';
      this.addNewForm.isStump='1'; // 是否根节点
      //新增根节点
      //使用  新增子项 同个弹窗 ，根据是否“根节点”  控制个别显隐
      this.showAddDialog = true
      this.isAddRoot = true
      this.addNewForm.name = '';
      this.addNewForm.pxRank = '';
    },

    // 新增子项
    addSon(row){

      let param={
        pageNo: this.search.pageNo,
        pageSize: this.search.pageSize,
        projectId: this.search.projectId,
        hiddenDangerCategoryId: row.id
      }

      this.$httpPost(`buss/inspectionQuestionItems/listPage`,param).then(res => {
        if (res.code == 200) {
          if(res.data.content.length>0){
            this.$messageError("该类别下已存在质量问题条目，不允许新建下级节点")
            return;
          }else {
            this.showAddDialog = true
            this.isAddRoot = false;
            this.$set(this,'chooseTreeData',row)
            this.addNewForm.fatherName = this.chooseTreeData.name
            this.addNewForm.isStump='0'; // 是否根节点
            this.addNewForm.pid = row.id;
            this.addNewForm.parentCode = row.code;
            this.addNewForm.treeRank = row.treeRank;
            this.addNewForm.isLeaf = '1';
            this.addNewForm.name = '';
            this.addNewForm.pxRank = '';
          }
        }else {
          this.$messageError(res.data.message)
        }
      })



    },


    edit(row){
      this.$set(this.editForm,'id', row.id)

      this.$set(this,'chooseTreeData',row)
      this.showEditDialog = true
      this.$nextTick(()=>{
        if(row.isLeaf=='1'){
          //是子节点
          this.editType = '子'
          this.$set(this.editForm,'name',this.chooseTreeData.name)
          this.$set(this.editForm,'isLeaf', row.isLeaf)
          this.$set(this.editForm,'pxRank', row.pxRank)
          this.$set(this.editForm,'pid', row.pid)
          //获取父节点内容
          this.getFatherBySon(row)
        }else{
          this.editType = '父'
          this.$set(this.editForm,'name',this.chooseTreeData.name)
          this.$set(this.editForm,'isLeaf', row.isLeaf)
          this.$set(this.editForm,'pxRank', row.pxRank)
        }
      })
      console.log(this.editForm)
    },
    del(row){
      console.log(row)
      //删除节点
      this.$confirm('确定是否删除？', '提示', {
        confirmButtonClass: 'iconfont icon-icon_ok',
        cancelButtonClass: 'iconfont icon-icon_cancel',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      })
        .then(() => {
          this.sealDealHttp(
            `buss/inspectionQuestionMain/del`,
            ``,
            { ids: row.id, },
            () => {
              this.$messageSuccess('删除成功!')
            }
          )
        })
    },

    // 事件处理的api请求
    sealDealHttp(url, query, param, callback) {
      this.$httpPost(url + query, param)
        .then((res) => {
          if (res.code === 200) {
            if (callback) callback(res)
            // 重新获取数据
            this.getTableData();
          } else {
            this.$messageError(res.message)
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          console.log(res)
        })
    },

    getFatherBySon(row){
      let node = this.$refs.allplanTable.data
      console.log(node)
      node.forEach((item,index)=>{
        if(item.childList){
          item.childList.forEach(val=>{
            if(row.id == val.id){
              this.$set(this,'chooseTreeFatherData',item)
              this.$set(this.editForm,'fatherName',item.name)
            }
          })
        }
      })
    },


    handleClickDeal(type, res, callback) {
      switch (type) {
        case 'cancel':
          this.$emit('reloadList')
          if( this.$refs['formBaseData']){
            this.$refs['formBaseData'].resetFields()
          }
          if( this.$refs['editFormBaseData']){
            this.$refs['editFormBaseData'].resetFields()
          }
            this.formShow = false
          break
        // 保存
        case 'submit':
          // 表单验证
          let flag = res.flag
          this.$refs['addNewForm'].validate((valid) => {
            if (valid) {
              // this.isLoading = true
              // 提交详情
              this.submitDetail(flag, () => {
                this.$emit('reloadList')
                this.formShow = false
              }).finally(() => {
                callback && callback();
              })
            } else {
              callback && callback();
            }
          })
          break

      }
    },

    // 提交详情 提交1/暂存0 新建0/修改1
    submitDetail(type, callback) {
      let submit='buss-measure/imageProgressBreakStump/submit'
      let resubmit='buss-measure/imageProgressBreakStump/resubmit'
      let url = this.detailType == 'build' ? submit : resubmit
      return this.$httpPost(url, this.addNewForm).then(res => {
        if (res.code == 200) {
          // this.formBaseData.id = res.data.data;
          this.detailId = res.data
          // this.saveFiles()
          this.$messageSuccess("保存成功")
        } else {
          this.$messageError(res.message);
        }
        if (callback) callback();
      }).catch(e => {
        console.log(e);
        this.$messageError("请求保存数据失败")
      })
    },


  }
}
</script>

<style scoped lang="scss">
  .fee_add {
    color: #008fe0;
    border-color: #008fe0;
    float: right;
    margin-bottom: 10px;
  }

  .el-input__inner {
    width: 291px;
  }
  .contract-ele {
    width: 90%;
  }

  .dialogTableDiv {
    width: 100%;
    margin: 0 auto;
    .tableTitle {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 15px;
      p {
        font-size: 16px;
      }
      .add {
        background-color: #ffffff;
        color: rgb(73, 163, 250);
      }
    }
  }

  .meterage-manage-detail
  .el-date-editor.el-input.el-input--prefix.el-input--suffix.el-date-editor--date {
    width: 255px;
  }
  .icon-add {
    position: absolute;
    top: 0;
    right: 0;
    color: #008fe0;
    font-size: 30px;
    cursor: pointer;
  }

  .icon-subtract {
    position: absolute;
    top: 0;
    right: 0;
    color: #008fe0;
    font-size: 30px;
    cursor: pointer;
  }
  .dialog-box {
    width: 100%;
    display: flex;
    flex-direction: column;
    // align-items: center;
    min-height: 500px;
    overflow-y: auto;
  }
  .actionSpan{
    display: flex;
    flex-direction: row;
    align-items: center;
    span{
      font-size: 17px;
    }
  }
  .rightButtonBox{
    width: 100%;display: flex;justify-content: flex-end;
    margin: 15px 0;
  }
</style>
